import { getAccount, createAccount, updateAccount, deleteAccount, updateUserPassword } from '@/api/account'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
// 权限判断指令
import permission from '@/directive/permission/index.js'

const defaultListQuery = {
  page: 1,
  limit: 10,
  ordering: '-id',
  is_company: 1,
  username: undefined,
  telephone: undefined,
  is_active: undefined,
  realname: undefined,
  roles: undefined
}

const defaultTemp = {
  id: undefined,
  username: '',
  password: '',
  checkPassword: '',
  real_name: undefined,
  telephone: undefined,
  is_active: true
}

const defaultForm = {
  user_id: '',
  new_password: '',
  checked_new_password: ''
}

export default {
  components: { Pagination },
  directives: { permission },
  filters: {
    typeFilter(type) {
      const typeMap = {
        true: '在职',
        false: '离职'
      }
      return typeMap[type]
    },
    statusFilter(status) {
      const statusMap = {
        true: 'success',
        false: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    var validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.temp.checkPassword !== '') {
          this.$refs.form.validateField('checkPassword')
        }
        callback()
      }
    }
    var validatePassword2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.temp.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    var validatePassword3 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.form.new_password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      rolesCheckedList: [],
      // 查询条件
      listQuery: Object.assign({}, defaultListQuery),
      // 账号状态
      statusList: [
        { label: '在职', value: true },
        { label: '离职', value: false }
      ],
      checkStrictly: false,
      defaultProps: {
        children: 'child',
        label: 'name'
      },
      roleTree: [],
      roleDialog: {
        accountId: undefined,
        visible: false,
        roleTree: []
      },
      temp: Object.assign({}, defaultTemp),
      accountDialogStatus: '',
      dialogFormVisible: false,
      textMap: {
        update: '编辑账号',
        create: '添加账号'
      },
      fileList: [],
      ExportVisible: false,
      createDialogRules: {
        username: [
          { required: true, message: '请输入登录账号', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
          { validator: validatePassword, trigger: 'blur' }
        ],
        checkPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
          { validator: validatePassword2, trigger: 'blur' }
        ]
      },
      updateDialogRules: {
        username: [
          { required: true, message: '请输入登录账号', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
        ]
      },
      resetPasswordDialogVisible: false,
      form: Object.assign({}, defaultForm),
      resetPasswordRulesList: {
        new_password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        checked_new_password: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validatePassword3, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    rulesList: function() {
      if (this.accountDialogStatus === 'create') {
        return this.createDialogRules
      } else {
        return this.updateDialogRules
      }
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.getList()
    },

    // 获取表格数据
    getList() {
      this.listLoading = true
      getAccount(this.listQuery).then(response => {
        this.list = response.results
        this.total = response.count

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      })
    },

    // 搜索事件
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },

    // 重置搜索条件
    resetFilter() {
      this.listQuery = Object.assign({}, defaultListQuery)
    },

    // 点击删除事件
    handleDelete(row, index) {
      this.$confirm('此操作将删除该账号, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAccount(row.id).then(res => {
          this.$message({
            type: 'success',
            message: '删除账号 ' + row.username + ' 成功!'
          })
          this.list.splice(index, 1)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    // 格式化, 将空的设为undefined, 为了让为空的数据不传入后台
    formatData(data) {
      for (var key in data) {
        if (data[key] === '') {
          data[key] = undefined
        }
      }
    },

    // 点击添加事件
    showCreateDialog() {
      this.temp = Object.assign({}, defaultTemp)
      this.accountDialogStatus = 'create'
      this.dialogFormVisible = true
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },

    // 进行添加
    createData() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys()
          const checkedKeys = this.$refs.tree.getCheckedKeys()
          const roles = halfCheckedKeys.concat(checkedKeys)
          if (roles.length > 0) {
            this.temp.roles = halfCheckedKeys.concat(checkedKeys)
          }
          this.formatData(this.temp)
          createAccount(this.temp).then(response => {
            this.list.unshift(response)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '新建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },

    // 点击修改事件
    showUpdateDialog(row) {
      this.temp = Object.assign({}, defaultTemp)
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.accountDialogStatus = 'update'
      this.dialogFormVisible = true
      // 保存一份初始的数据, 方便提交的时候进行对比, 只更新已经修改过的字段
      this.originRowData = JSON.parse(JSON.stringify(row)) // 深拷贝, 不能Object.assign, 因为row是两层
      this.temp = Object.assign({}, row)
      this.$nextTick(function() {
        row.roles.forEach(i => {
          const node = this.$refs.tree.getNode(i)
          if (node.isLeaf) {
            this.$refs.tree.setChecked(node, true)
          }
        })
        this.$refs['form'].clearValidate()
      })
    },
    // 对初始数据和将提交数据进行对比, 只提交已经修改过的字段
    diffTwoData(originRow, newRow) {
      var results = {}
      for (var key in newRow) {
        if (newRow[key] !== originRow[key]) {
          // newRow[key] = undefined
          results[key] = newRow[key]
        }
      }
      return results
    },

    // 进行修改
    updateData() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          var request_data = this.diffTwoData(this.originRowData, this.temp)
          const halfCheckedKeys = this.$refs.tree.getHalfCheckedKeys()
          const checkedKeys = this.$refs.tree.getCheckedKeys()
          this.temp.roles = halfCheckedKeys.concat(checkedKeys)
          var tmp1 = this.temp.roles.sort().toString()
          var tmp2 = this.originRowData.roles.sort().toString()
          if (tmp1 === tmp2) {
            this.temp.roles = undefined
          }
          if (tmp2.length > 0 && tmp1.length === 0) {
            this.temp.roles = []
          }
          request_data['roles'] = this.temp.roles
          request_data['grade_group'] = '初中'

          updateAccount(this.temp.id, request_data).then(response => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, response)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },

    // 点击重置密码事件
    showResetPasswordDialog(row) {
      this.form = Object.assign({}, defaultForm)
      this.form.user_id = row.id
      this.resetPasswordDialogVisible = true
      this.$nextTick(() => {
        this.$refs['resetForm'].clearValidate()
      })
    },
    handleResetPassword() {
      this.$refs['resetForm'].validate((valid) => {
        if (valid) {
          updateUserPassword(this.form.user_id, this.form).then(response => {
            this.resetPasswordDialogVisible = false
            this.$notify({
              title: '成功',
              message: response.message,
              type: 'success',
              duration: 2000
            })
          }).catch((error) => {
            this.$notify({
              title: '错误',
              message: error.response.data,
              type: 'error',
              duration: 0
            })
          })
        }
      })
    }

    // // 点击角色分配
    // openRole(row) {
    //   if (this.$refs.tree) {
    //     this.$refs.tree.setCheckedNodes([])
    //   }
    //   // this.originRole = JSON.parse(JSON.stringify(row)) // 深拷贝, 不能Object.assign, 因为row是两层
    //   // this.role = row
    //   this.roleDialog.visible = true
    //   this.roleDialog.accountId = row.id
    //   // this.rolesCheckedList = row.roles
    //   // 设置勾选的节点, 只设置叶子节点
    //   this.$nextTick(function() {
    //     row.roles.forEach(i => {
    //       const node = this.$refs.tree.getNode(i)
    //       if (node.isLeaf) {
    //         this.$refs.tree.setChecked(node, true)
    //       }
    //     })
    //   })
    // },

    // // 进行角色分配
    // setRole() {
    //   setRoles(this.roleDialog.accountId, this.rolesCheckedList).then(response => {
    //     const index = this.list.findIndex(v => v.id === this.roleDialog.accountId)
    //     this.list.splice(index, 1, response)
    //     this.roleDialog.visible = false
    //     this.$notify({
    //       title: '成功',
    //       message: '成功分配角色',
    //       type: 'success',
    //       duration: 2000
    //     })
    //   })
    // },

    // // 导出Excel事件
    // downloadExcel() {
    //   // list保存的是当前页面的数据, 要导出全部数据需要重写条件请求全部数据
    //   var listQuery = Object.assign({}, this.listQuery)
    //   listQuery.page = undefined
    //   listQuery.limit = undefined
    //   getAccount(listQuery).then(response => {
    //     const list = response
    //     import('@/vendor/Export2Excel').then(excel => {
    //       const tHeader = ['账号', '姓名', '手机号']
    //       const filterVal = ['username', 'realname', 'telephone']
    //       const data = this.formatJson(filterVal, list)
    //       console.log(data)
    //       excel.export_json_to_excel({
    //         header: tHeader,
    //         data,
    //         filename: '账号表',
    //         autoWidth: true
    //       })
    //     })
    //   })
    // },
    // formatJson(filterVal, jsonData) {
    //   return jsonData.map(v => filterVal.map(j => {
    //     return v[j]
    //   }))
    // },

    // 点击导入Excel事件
    // showExportDialog() {
    //   this.ExportVisible = true
    // },

    // // 上传文件之前的钩子
    // beforeUpload(file) {
    //   const type = file.name.split('.')[1]
    //   if (type !== 'xlsx' && type !== 'xls') {
    //     this.$message.error('请上传后缀名为 .xlsx 或 .xls 的excel文件')
    //     return false
    //   }
    //   // 限制文件上传大小, 大于1M则提示, 且不请求提交表单
    //   const isLt1M = file.size / 1024 / 1024 < 1
    //   if (!isLt1M) {
    //     this.$message.error('上传文件大小不能超过1M')
    //     return false
    //   }
    // },
    // // 上传文件数量超出自定义数量
    // handleExceed(files, fileList) {
    //   this.$message.warning('当前限制选择 1 个文件, 请删除后继续上传')
    // },
    // // 点击上传事件
    // submitUpload() {
    //   this.$refs.upload.submit()
    // },
    // uploadFile(item) {
    //   const file = item.file
    //   const form = new FormData()
    //   form.append('upload', file)
    //   uploadExcel(form).then(response => {
    //     this.$notify({
    //       title: '上传文件成功',
    //       message: '上传文件成功',
    //       type: 'success',
    //       duration: 2000
    //     })
    //   })
    // }

  }
}
